// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import path = require('path');
import * as vscode from 'vscode';
import 'isomorphic-fetch';
import * as GiteeProvider from './provider/gitee/index';
import * as Token from './tokens';
import { Git } from './git';

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
  /** 是否是 npm pacakge  */
  // const isPackageRoot = (): boolean => { return true; };
  /** 获取 package 名称 */
  const getPackageName = (pkg: any): string => { return pkg.name; };
  const getPackageDesc = (pkg: any): string => { return pkg.description; };

  // Use the console to output diagnostic information (console.log) and errors (console.error)
  // This line of code will only be executed once when your extension is activated
  console.log('Congratulations, your extension "gitee" is now active!');

  const isSetToken = ()=> Token.getToken(context.globalState);

  const checkToken = (): boolean => {
    if (!isSetToken()) {
      vscode.window.showInformationMessage(
        '该命令需先添加 access token 后才能操作。'
      );
      return false;
    }
    return true;
  };

  /**
   *
   * @param isPrivate 是否是私有
   */
  const commandHandlerCreateRepo = async (isPrivate: boolean) => {
    if (!checkToken()) {
      return;
    }
    const pkg = {};
    const pkgName = getPackageName(pkg);
    // The code you place here will be executed every time your command is executed
    const name = await vscode.window.showInputBox({
      value: pkgName ? pkgName : '',
      ignoreFocusOut: true,
      placeHolder: '命名仓库',
    });

    const pkgDesc = getPackageDesc(pkg);
    const description = await vscode.window.showInputBox({
      value: pkgDesc ? pkgDesc : '',
      ignoreFocusOut: true,
      placeHolder: '仓库描述',
    });

    if (name) {
      GiteeProvider.createRepository(context.globalState, {
        name,
        description,
        isPrivate,
      })
        .then((resp) => {
          const {
            body: {
              ssh_url,
            },
          } = resp as any;
          vscode.window.showInformationMessage(`Gitee：成功创建仓库 ${name}！\n${ssh_url}`);
        })
        .catch(err => {
          console.error(err);
          vscode.window.showErrorMessage('Gitee error: ' + err.message);
        });
    }
  };

  // The command has been defined in the package.json file
  // Now provide the implementation of the command with registerCommand
  // The commandId parameter must match the command field in package.json
  let disposablePrivate = vscode.commands.registerCommand('gitee.createPrivateRepository', () => {
    commandHandlerCreateRepo(true);
  });
  let disposablePublic = vscode.commands.registerCommand('gitee.createPublicRepository', () => {
    commandHandlerCreateRepo(false);
  });

  context.subscriptions.push(disposablePrivate);
  context.subscriptions.push(disposablePublic);

  /** 添加 access token */
  let disposableToken = vscode.commands.registerCommand('gitee.addAccessToken', async () => {
    const options = {
      ignoreFocusOut: true,
      password: true,
      placeHolder: 'Gitee Access Token'
    };

    const input = await vscode.window.showInputBox(options);
    if (input) {
      Token.setToken(context.globalState, 'gitee', input);
      // Display a message box to the user
      vscode.window.showInformationMessage('Gitee: 成功添加 access token！');
    }
    else {
      vscode.window.showErrorMessage('Gitee: 请先添加 access token');
    }

  });

  /** 删除 access token */
  let disposableRemoveToken = vscode.commands.registerCommand('gitee.removeAccessToken', async () => {
    if (!isSetToken()) {
      vscode.window.showInformationMessage(
        'Gitee: 并未设置 access token 。'
      );
      return;
    }

    vscode.window.showInformationMessage('Gitee: 您确定要移除 access token ?', {
      modal: true,
    }, '移除').then((action)=>{
      if( action === '移除'){
        Token.removeToken(context.globalState, 'gitee');
        vscode.window.showInformationMessage('Gitee: 成功移除 access token ！');
      }
    });

  });
  context.subscriptions.push(disposableToken);
  context.subscriptions.push(disposableRemoveToken);

  /**
   * 创建代码片段
   * @param textEditor
   * @param isPublic 是否是公开
   */
  const commandHandlerCreateGist = async (textEditor: vscode.TextEditor, isPublic: boolean) => {
    if (!checkToken()) {
      return;
    }
    // current editor
    const editor = textEditor;
    const document = editor?.document;
    let file: string | undefined = document?.fileName.split(path.sep).pop();
    const content = document?.getText().trim();


    const optionsFile = {
      ignoreFocusOut: true,
      placeHolder: '代码片段名称',
      value: file || '',
    };
    file = await vscode.window.showInputBox(optionsFile);

    if (!file) {
      vscode.window.showErrorMessage('代码片段名称不能为空！');
      return;
    }

    if (!content) {
      vscode.window.showErrorMessage('代码片段内容不能为空！');
      return;
    }

    const options = {
      ignoreFocusOut: true,
      placeHolder: '代码片段描述'
    };
    const description = await vscode.window.showInputBox(options);

    if (!description) {
      vscode.window.showErrorMessage('代码片段描述不能为空！');
      return;
    }

    GiteeProvider.createGist(context.globalState, {
      file,
      content,
      description,
      isPublic,
    })
      .then((resp) => {
        const {
          body: {
            html_url,
          },
        } = resp as any;
        vscode.window.showInformationMessage(`Gitee：成功创建代码片段 ${file}！\n${html_url}`);
      })
      .catch(err => {
        console.error(err);
        vscode.window.showErrorMessage('Gitee error: ' + err.message);
      });

  };

  let disposableGistPublic = vscode.commands.registerTextEditorCommand('gitee.createPublicGist', (textEditor: vscode.TextEditor,) => {
    commandHandlerCreateGist(textEditor, true);
  });
  let disposableGistPrivate = vscode.commands.registerTextEditorCommand('gitee.createPrivateGist', (textEditor: vscode.TextEditor,) => {
    commandHandlerCreateGist(textEditor, false);
  });

  context.subscriptions.push(disposableGistPublic);
  context.subscriptions.push(disposableGistPrivate);

  let disposableRepoPage = vscode.commands.registerCommand('gitee.openRepoPage', () => {
    const folders = vscode.workspace.workspaceFolders;
    if (folders?.length === 1) {
      const uri = folders[0].uri;
      const git = new Git();
      git.openRepositoryUrl(uri);
    }
  });
  context.subscriptions.push(disposableRepoPage);

  console.log('Gitee: Hello World !');
}

// this method is called when your extension is deactivated
export function deactivate() { }
